package top.broncho.gank.ui.fragment

import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.fragment.app.viewModels
import androidx.recyclerview.widget.DefaultItemAnimator
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.chad.library.adapter.base.BaseQuickAdapter
import top.broncho.gank.R
import top.broncho.gank.adapter.TodoAdapter
import top.broncho.gank.app.App
import top.broncho.gank.bean.TodoDataBean
import top.broncho.gank.bean.TodoResponseBody
import top.broncho.gank.constant.Constant
import top.broncho.gank.databinding.FragmentTodoBinding
import top.broncho.gank.ext.showSnackMsg
import top.broncho.gank.ext.showToast
import top.broncho.gank.ui.activity.CommonActivity
import top.broncho.gank.utils.DialogUtil
import top.broncho.gank.utils.NetWorkUtil
import top.broncho.gank.widget.SpaceItemDecoration
import top.broncho.gank.widget.SwipeItemLayout
import kotlinx.android.synthetic.main.fragment_refresh_layout.*
import top.broncho.mvvm.base.BaseDiFragment

/**
 * Created by chenxz on 2018/8/6.
 */

class TodoFragment : BaseDiFragment<FragmentTodoBinding>() {

    companion object {
        fun getInstance(type: Int): TodoFragment {
            val fragment = TodoFragment()
            val bundle = Bundle()
            bundle.putInt(Constant.TODO_TYPE, type)
            fragment.arguments = bundle
            return fragment
        }
    }

    private val viewModel by viewModels<TodoViewModel> { viewModelFactory }

    /**
     * 每页数据的个数
     */
    protected var pageSize = 20

    /**
     * 是否是下拉刷新
     */
    protected var isRefresh = true

    /**
     * LinearLayoutManager
     */
    protected val linearLayoutManager: LinearLayoutManager by lazy {
        LinearLayoutManager(requireContext())
    }

    /**
     * RecyclerView Divider
     */
    private val recyclerViewItemDecoration by lazy {
        SpaceItemDecoration(requireContext())
    }

    /**
     * RefreshListener
     */
    protected val onRefreshListener = SwipeRefreshLayout.OnRefreshListener {
        isRefresh = true
        onRefreshList()
    }

    /**
     * LoadMoreListener
     */
    protected val onRequestLoadMoreListener = BaseQuickAdapter.RequestLoadMoreListener {
        isRefresh = false
        swipeRefreshLayout.isRefreshing = false
        onLoadMoreList()
    }


    private var mType: Int = 0

    /**
     * 是否是已完成 false->待办 true->已完成
     */
    private var bDone: Boolean = false

    private val datas = mutableListOf<TodoDataBean>()

    private val mAdapter: TodoAdapter by lazy {
        TodoAdapter(R.layout.item_todo_list, R.layout.item_sticky_header, datas)
    }

    fun hideLoading() {
        if (isRefresh) {
            mAdapter.setEnableLoadMore(true)
        }
    }

    fun showError(errorMsg: String) {
        if (isRefresh) {
            mAdapter.setEnableLoadMore(true)
        } else {
            mAdapter.loadMoreFail()
        }
    }

    override fun getLayoutId(): Int = R.layout.fragment_todo

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView(view)
        if (bDone) {
            viewModel.doneTodoList.observe({ lifecycle }) {
                swipeRefreshLayout.isRefreshing = false
                if(it.isFailure) {
                    showError(it.exceptionOrNull().toString())
                    return@observe
                }
                mLayoutStatusView?.showContent()
                showNoTodoList(it.getOrThrow())
            }
        } else {
            viewModel.noTodoList.observe({ lifecycle }) {
                swipeRefreshLayout.isRefreshing = false
                if(it.isFailure) {
                    showError(it.exceptionOrNull().toString())
                    return@observe
                }
                mLayoutStatusView?.showContent()
                showNoTodoList(it.getOrThrow())
            }
        }
    }

    fun initView(view: View) {
        mLayoutStatusView = multiple_status_view
        swipeRefreshLayout.run {
            setOnRefreshListener(onRefreshListener)
        }
        recyclerView.run {
            layoutManager = linearLayoutManager
            adapter = mAdapter
            itemAnimator = DefaultItemAnimator()
            addItemDecoration(recyclerViewItemDecoration)
        }
        mType = arguments?.getInt(Constant.TODO_TYPE) ?: 0

        recyclerView.run {
            adapter = mAdapter
            addOnItemTouchListener(SwipeItemLayout.OnSwipeItemTouchListener(activity))
        }

        mAdapter.run {
            bindToRecyclerView(recyclerView)
            setOnLoadMoreListener(onRequestLoadMoreListener, recyclerView)
            onItemClickListener = this@TodoFragment.onItemClickListener
            onItemChildClickListener = this@TodoFragment.onItemChildClickListener
            // setEmptyView(R.layout.fragment_empty_layout)
        }

    }

    override fun onResume() {
        super.onResume()
        if (bDone) {
            if (viewModel.doneTodoList.value == null) {
                lazyLoad()
            }
        } else {
            if (viewModel.noTodoList.value == null) {
                lazyLoad()
            }
        }
    }

    fun lazyLoad() {
        mLayoutStatusView?.showLoading()
        if (bDone) {
            viewModel.getDoneList(1, mType)
        } else {
            viewModel.getNoTodoList(1, mType)
        }
    }

    fun onRefreshList() {
        mAdapter.setEnableLoadMore(false)
        lazyLoad()
    }

    fun onLoadMoreList() {
        val page = mAdapter.data.size / pageSize + 1
        if (bDone) {
            viewModel.getDoneList(page, mType)
        } else {
            viewModel.getNoTodoList(page, mType)
        }
    }

    public fun onTodoChange(type: Int, done: Boolean) {
        mType = type
        bDone = done
        lazyLoad()
    }

//    fun doTodoEvent(event: TodoEvent) {
//        if (mType == event.curIndex) {
//            when (event.type) {
//                Constant.TODO_ADD -> {
//                    Intent(activity, CommonActivity::class.java).run {
//                        putExtra(Constant.TYPE_KEY, Constant.Type.ADD_TODO_TYPE_KEY)
//                        putExtra(Constant.TODO_TYPE, mType)
//                        startActivity(this)
//                    }
//                }
//                Constant.TODO_NO -> {
//                    bDone = false
//                    lazyLoad()
//                }
//                Constant.TODO_DONE -> {
//                    bDone = true
//                    lazyLoad()
//                }
//            }
//        }
//    }
//
//    fun doRefresh(event: RefreshTodoEvent) {
//        if (event.isRefresh) {
//            if (mType == event.type) {
//                lazyLoad()
//            }
//        }
//    }

    fun showNoTodoList(todoResponseBody: TodoResponseBody) {
        // TODO 待优化
        val list = mutableListOf<TodoDataBean>()
        var bHeader = true
        todoResponseBody.datas.forEach { todoBean ->
            bHeader = true
            for (i in list.indices) {
                if (todoBean.dateStr == list[i].header) {
                    bHeader = false
                    break
                }
            }
            if (bHeader)
                list.add(TodoDataBean(true, todoBean.dateStr))
            list.add(TodoDataBean(todoBean))
        }

        list.let {
            mAdapter.run {
                if (isRefresh) {
                    replaceData(it)
                } else {
                    addData(it)
                }
                pageSize = todoResponseBody.size
                if (todoResponseBody.over) {
                    loadMoreEnd(isRefresh)
                } else {
                    loadMoreComplete()
                }
            }
        }
        if (mAdapter.data.isEmpty()) {
            mLayoutStatusView?.showEmpty()
        } else {
            mLayoutStatusView?.showContent()
        }
    }

    fun showDeleteSuccess(success: Boolean) {
        if (success) {
            showToast(resources.getString(R.string.delete_success))
        }
    }

    fun showUpdateSuccess(success: Boolean) {
        if (success) {
            showToast(resources.getString(R.string.completed))
        }
    }

    /**
     * ItemClickListener
     */
    private val onItemClickListener = BaseQuickAdapter.OnItemClickListener { _, _, position ->
        if (datas.size != 0) {
            val data = datas[position]
        }
    }

    /**
     * ItemChildClickListener
     */
    private val onItemChildClickListener =
        BaseQuickAdapter.OnItemChildClickListener { _, view, position ->
            if (datas.size != 0) {
                val data = datas[position].t
                when (view.id) {
                    R.id.btn_delete -> {
                        if (!NetWorkUtil.isNetworkAvailable(App.context)) {
                            showSnackMsg(resources.getString(R.string.no_network))
                            return@OnItemChildClickListener
                        }
                        activity?.let {
                            DialogUtil.getConfirmDialog(it,
                                resources.getString(R.string.confirm_delete),
                                DialogInterface.OnClickListener { _, _ ->
                                    viewModel.deleteTodoById(data.id)
                                    mAdapter.remove(position)
                                }).show()
                        }
                    }
                    R.id.btn_done -> {
                        if (!NetWorkUtil.isNetworkAvailable(App.context)) {
                            showSnackMsg(resources.getString(R.string.no_network))
                            return@OnItemChildClickListener
                        }
                        if (bDone) {
                            viewModel.updateTodoById(data.id, 0)
                        } else {
                            viewModel.updateTodoById(data.id, 1)
                        }
                        mAdapter.remove(position)
                    }
                    R.id.item_todo_content -> {
                        if (bDone) {
                            Intent(activity, CommonActivity::class.java).run {
                                putExtra(Constant.TYPE_KEY, Constant.Type.SEE_TODO_TYPE_KEY)
                                putExtra(Constant.TODO_BEAN, data)
                                putExtra(Constant.TODO_TYPE, mType)
                                startActivity(this)
                            }
                        } else {
                            Intent(activity, CommonActivity::class.java).run {
                                putExtra(Constant.TYPE_KEY, Constant.Type.EDIT_TODO_TYPE_KEY)
                                putExtra(Constant.TODO_BEAN, data)
                                putExtra(Constant.TODO_TYPE, mType)
                                startActivity(this)
                            }
                        }
                    }
                }
            }
        }

}